<template>
  <a-date-picker
    v-model:value="newValue"
    @change="handleChange"
    :picker="picker"
    :placeholder="placeholder"
    :style="{ width: width }"
  />
</template>

<script setup>
import { defineProps, defineEmits, watch } from 'vue'
import { ref, inject } from 'vue'
const dayjs = inject('dayjs')
const props = defineProps({
  value: {
    type: null,
    default: null,
  },
  placeholder: {
    type: String,
    default: '请选择',
  },
  width: {
    type: String,
    default: '',
  },
	picker: {
		type: String,
		default: 'year'	
	}
})
const newValue = ref()
newValue.value = props.value ? props.picker == 'year' ? dayjs(`${props.value}/01`) : dayjs(`${props.value}`) : ''

watch(() => props.value, (newval) => {
  newValue.value = props.value ? props.picker == 'year' ? dayjs(`${props.value}/01`) : dayjs(`${props.value}`) : ''
})
const emit = defineEmits(['update:value', 'handleChange'])

const handleChange = (date) => {
  // date | week | month | quarter | year
let formatObj = {
  date: 'YYYY-MM-DD',
  month: 'YYYY-MM',
  week: 'MM-DD',
  year: 'YYYY'
}
let val = date ? date.format(formatObj[props.picker] || 'YYYY-MM-DD') : null
  emit('update:value', val)
  emit('handleChange', val)
}
</script>